package com.fone.player.activity.personal.adapter;

import java.util.LinkedHashMap;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.fone.player.R;
import com.fone.player.activity.personal.CacheActivity;
import com.fone.player.cache.ImageDownloadModule;
import com.fone.player.constant.FoneConstant;
import com.fone.player.entity.OfflineCache;
import com.fone.player.storage.SharedPreferenceModule;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.SystemUtil;
import com.fone.player.widget.xlistview.XListView;

/**
 * 缓存主界面adapter,与收藏不同在于没有checebox。
 * 
 * @author JasonZue
 * @since 2014-4-22
 */
public class CacheListAdatper extends BaseAdapter {
	private static final String TAG = CacheListAdatper.class.getSimpleName();
	private XListView mCacheListView = null;
	private List<OfflineCache> mOfflineCacheList;
	private Context mContext;
	private Handler mHandler;
	private LinkedHashMap<Long, Integer> mFolderOfflineCacheMap = new LinkedHashMap<Long, Integer>();
	private LinkedHashMap<Long, Integer> mFileOfflineCacheMap = new LinkedHashMap<Long, Integer>();
	// 是否加载视图(getView)
	private boolean mIsInitGetView = false;

	/**
	 * @param mContext
	 * @param collectionData
	 *            传入条目数据List
	 * @param autoDownload
	 *            传入记录选中下载的list对象
	 */
	public CacheListAdatper(Context mContext) {
		this.mContext = mContext;
	}

	public CacheListAdatper(Context mContext, Handler mHandler) {
		this.mContext = mContext;
		this.mHandler = mHandler;
	}

	public void setOfflineCacheList(List<OfflineCache> offlineCacheList) {
		this.mOfflineCacheList = offlineCacheList;
	}

	@Override
	public int getCount() {
		return mOfflineCacheList != null ? mOfflineCacheList.size() : 0;
	}

	@Override
	public Object getItem(int position) {
		return mOfflineCacheList != null ? mOfflineCacheList.get(position)
				: null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = View.inflate(mContext,
					R.layout.personal_cache_list_item, null);

			holder.selectedCb = (CheckBox) convertView
					.findViewById(R.id.cache_is_selected_cb);
			holder.mPlayBt = (ImageButton) convertView
					.findViewById(R.id.collection_listview_item_play_ib);
			holder.downloadStatusTv = (TextView) convertView
					.findViewById(R.id.collection_listview_item_download_status_tv);
			holder.seasonInfo = (TextView) convertView
					.findViewById(R.id.collection_listview_item_season_tv);
			holder.collectionType = (TextView) convertView
					.findViewById(R.id.collection_listview_item_collection_type_tv);
			holder.downloadedSize = (TextView) convertView
					.findViewById(R.id.collection_listview_item_downloaded_tv);
			holder.totalSize = (TextView) convertView
					.findViewById(R.id.collection_listview_item_totle_progress_tv);
			holder.upDateInfo = (TextView) convertView
					.findViewById(R.id.collection_listview_item_update_info_tv);
			holder.itemImage = (ImageView) convertView
					.findViewById(R.id.collection_listview_item_pic_iv);
			holder.itemName = (TextView) convertView
					.findViewById(R.id.collection_listview_item_name_tv);
			holder.downloadProgressBar = (ProgressBar) convertView
					.findViewById(R.id.collection_listview_item_progressbar_pb);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		// 记录索引位置
		OfflineCache offlineCache = mOfflineCacheList.get(position);
		if (offlineCache != null) {
			switch (offlineCache.getCacheContentType()) {
			case OfflineCache.CACHE_CONTENT_TYPE_ANIMATION:
			case OfflineCache.CACHE_CONTENT_TYPE_TV:
			case OfflineCache.CACHE_CONTENT_TYPE_VARIETY:
				// 剧集类
				switch (offlineCache.getCacheHierarchyType()) {
				case OfflineCache.CACHE_HIERARCHY_FOLDER:
					L.v(TAG, "setViewData",
							"CACHE_HIERARCHY_FOLDER hashmap name="
									+ offlineCache.getCacheName()
									+ offlineCache.getCacheEpisodeNum()
									+ " ccid=" + offlineCache.getCacheCCID()
									+ " position=" + position);
					// 记录缓存当前位置
					mFolderOfflineCacheMap.put(offlineCache.getCacheCCID(),
							Integer.valueOf(position));
					break;
				case OfflineCache.CACHE_HIERARCHY_FILE:
					L.v(TAG,
							"setViewData",
							"CACHE_HIERARCHY_FILE hashmap name="
									+ offlineCache.getCacheName()
									+ offlineCache.getCacheEpisodeNum()
									+ " cid=" + offlineCache.getCacheCID()
									+ " position=" + position);
					// 记录缓存当前位置
					mFileOfflineCacheMap.put(offlineCache.getCacheCID(),
							Integer.valueOf(position));
					break;
				}
				break;
			default:
				// 非剧集
				L.v(TAG,
						"setViewData",
						"CACHE_HIERARCHY_FOLDER hashmap name="
								+ offlineCache.getCacheName()
								+ offlineCache.getCacheEpisodeNum() + " ccid="
								+ offlineCache.getCacheCCID() + " position="
								+ position);
				// 记录缓存当前位置
				mFolderOfflineCacheMap.put(offlineCache.getCacheCCID(),
						Integer.valueOf(position));
				break;

			}

		}

		// 设置数据
		setViewData(position, holder);

		// 标记getView已经加载
		mIsInitGetView = true;

		return convertView;

	}

	/**
	 * 
	 * 设置视图数据
	 * 
	 * @param position
	 *            当前索引
	 * @param holder
	 *            控制类
	 * @return void
	 */
	private void setViewData(final int position, final ViewHolder holder) {
		final OfflineCache offlineCache = mOfflineCacheList.get(position);
		if (null != offlineCache) {

			holder.itemName.setText(offlineCache.getCacheName());
			holder.seasonInfo.setText(offlineCache.getCacheEpisodeNum());

			switch (offlineCache.getCacheContentType()) {
			case OfflineCache.CACHE_CONTENT_TYPE_ANIMATION:
			case OfflineCache.CACHE_CONTENT_TYPE_TV:
			case OfflineCache.CACHE_CONTENT_TYPE_VARIETY:
				// 剧集类
				switch (offlineCache.getCacheHierarchyType()) {
				case OfflineCache.CACHE_HIERARCHY_FOLDER:

					holder.downloadedSize.setText(offlineCache
							.getCacheFinishCount() + "集");
					holder.totalSize.setText("/"
							+ offlineCache.getCacheAllCount() + "集");
					if (offlineCache.getCacheAllCount() != 0) {
						holder.downloadProgressBar
								.setProgress(mOfflineCacheList.get(position)
										.getCacheFinishCount()
										* 100
										/ offlineCache.getCacheAllCount());
					} else {
						holder.downloadProgressBar.setProgress(0);
					}
					break;
				case OfflineCache.CACHE_HIERARCHY_FILE:

					if (offlineCache.getCacheAlreadySize() == 0) {
						holder.downloadedSize.setText("");
						holder.totalSize.setText("");
						holder.downloadProgressBar.setProgress(0);
					} else {

						holder.downloadedSize.setText(Formatter.formatFileSize(
								mContext, offlineCache.getCacheAlreadySize()));
						holder.totalSize.setText("/"
								+ Formatter.formatFileSize(mContext,
										offlineCache.getCacheTotalSize()));

						try {
							int progress = 0;
							if (offlineCache.getCacheTotalSize() > 0) {
								progress = (int) (100 * offlineCache
										.getCacheAlreadySize() / offlineCache
										.getCacheTotalSize());
							}

							holder.downloadProgressBar.setProgress(progress);

						} catch (Exception e) {
							e.printStackTrace();
							holder.downloadProgressBar.setProgress(0);
						}

					}
					break;
				}
				break;
			case OfflineCache.CACHE_CONTENT_TYPE_LIVE_AUDIO:
			case OfflineCache.CACHE_CONTENT_TYPE_LIVE_VIDEO:
			case OfflineCache.CACHE_CONTENT_TYPE_MOVIE:
			case OfflineCache.CACHE_CONTENT_TYPE_NEWS:
			case OfflineCache.CACHE_CONTENT_TYPE_ORIGINAL:
			case OfflineCache.CACHE_CONTENT_TYPE_SHORT_FILM:
			case OfflineCache.CACHE_CONTENT_TYPE_OTHER:
				// 非剧集类

				if (offlineCache.getCacheAlreadySize() == 0) {
					holder.downloadedSize.setText("");
					holder.totalSize.setText("");
					holder.downloadProgressBar.setProgress(0);
				} else {
					holder.downloadedSize.setText(Formatter.formatFileSize(
							mContext, offlineCache.getCacheAlreadySize()));
					holder.totalSize.setText("/"
							+ Formatter.formatFileSize(mContext,
									offlineCache.getCacheTotalSize()));
					holder.downloadProgressBar
							.setProgress((int) (100 * offlineCache
									.getCacheAlreadySize() / mOfflineCacheList
									.get(position).getCacheTotalSize()));
				}
				break;
			default:
				break;

			}
			// 设置图片
			if (!TextUtils.isEmpty(offlineCache.getCacheImageUrl())) {
				ImageDownloadModule.getInstance().download(
						offlineCache.getCacheImageUrl(), holder.itemImage);
			}

			// L.v(TAG, "setViewData", "name=" + offlineCache.getCacheName()
			// + offlineCache.getCacheEpisodeNum() + " alreadySize="
			// + offlineCache.getCacheAlreadySize() + " totalSize="
			// + offlineCache.getCacheTotalSize());

			// 设置文字和图片
			if (offlineCache.getCacheIsPlay()
					&& offlineCache.getCacheDownloadState() != OfflineCache.CACHE_STATE_FINISH) {
				holder.mPlayBt.setVisibility(View.VISIBLE);
			} else {
				holder.mPlayBt.setVisibility(View.GONE);
			}
			holder.upDateInfo.setText(offlineCache.getCacheEpisodeUpdateInfo());

			switch (offlineCache.getCacheDownloadState()) {
			case OfflineCache.CACHE_STATE_WAITING:
			case OfflineCache.CACHE_STATE_QWAITING:
				changeStatus(holder, R.drawable.collect_icon_wait,
						R.color.cache_item_status_text_color, "等待中", true);
				break;
			case OfflineCache.CACHE_STATE_PAUSE_USER:
			case OfflineCache.CACHE_STATE_PAUSE:
				changeStatus(holder, R.drawable.collect_icon_pause,
						R.color.cache_item_status_text_color, "暂停", true);
				break;
			case OfflineCache.CACHE_STATE_DOWNLOADING:
				L.v(TAG, "setViewData", "CACHE_STATE_DOWNLOADING");
				changeStatus(holder, R.drawable.collect_icon_download,
						R.color.cache_item_status_text_color, "下载中", true);
				break;
			case OfflineCache.CACHE_STATE_FINISH:
				changeStatus(holder, R.drawable.collect_icon_download,
						R.color.cache_item_green_color, "已完成", false);
				break;
			case OfflineCache.CACHE_STATE_ERROR:
				changeStatus(holder, R.drawable.collect_icon_wait,
						R.color.cache_item_status_text_color, "出错", true);
				// 出错状态下 不显示可播放按钮
				holder.mPlayBt.setVisibility(View.GONE);
				break;
			case OfflineCache.CACHE_STATE_NOT_DOWNLOAD:
				changeStatus(holder, R.drawable.collect_icon_wait,
						R.color.cache_item_status_text_color, "", false);
				break;
			default:
				changeStatus(holder, R.drawable.collect_icon_wait,
						R.color.cache_item_status_text_color, "", false);
				break;
			}

			// 设置图片文字
			switch (offlineCache.getCacheContentType()) {
			case OfflineCache.CACHE_CONTENT_TYPE_TV:
				holder.collectionType.setText("电视剧");
				break;
			case OfflineCache.CACHE_CONTENT_TYPE_WEB_PAGE:
				holder.collectionType.setText("网页");
				break;
			case OfflineCache.CACHE_CONTENT_TYPE_MOVIE:
				holder.collectionType.setText("电影");
				break;
			case OfflineCache.CACHE_CONTENT_TYPE_ANIMATION:
				holder.collectionType.setText("动漫");
				break;
			case OfflineCache.CACHE_CONTENT_TYPE_SHORT_FILM:
				holder.collectionType.setText("短剧");
				break;
			case OfflineCache.CACHE_CONTENT_TYPE_NEWS:
				holder.collectionType.setText("新闻");
				break;
			case OfflineCache.CACHE_CONTENT_TYPE_LIVE_AUDIO:
				holder.collectionType.setText("直播音频");
				break;
			case OfflineCache.CACHE_CONTENT_TYPE_LIVE_VIDEO:
				holder.collectionType.setText("直播");
				break;
			case OfflineCache.CACHE_CONTENT_TYPE_ORIGINAL:
				holder.collectionType.setText("原创");
				break;
			case OfflineCache.CACHE_CONTENT_TYPE_VARIETY:
				holder.collectionType.setText("综艺");
				break;
			case OfflineCache.CACHE_CONTENT_TYPE_OTHER:
				holder.collectionType.setText("其他");
				break;
			default:
				holder.collectionType.setText("未知");
				break;
			}
		}

		holder.mPlayBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 点击播放实现边下边看
				Message message = mHandler
						.obtainMessage(CacheActivity.DOWNLOAD_WHILE_PLAY);
				message.obj = offlineCache;
				mHandler.sendMessage(message);

			}
		});

		holder.downloadStatusTv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 修改点击后的下载状态
				/*
				 * 下载状态一共有5种:下载,暂停,完成,等待,出错 其中手动可操作的状态只有: 下载->暂停 等待->暂停 暂停->下载
				 * 出错->下载 其他状态的改变应该为代码修改,如:下载->等待(在已下载任务已经到最大值时) 添加一个新的状态
				 * 操作中(用于处理状态中间的切换)
				 */

				// 判断网络
				if (FoneUtil.isNetOkWithToast(mContext)) {
					long freeSpace = SystemUtil.getInstance().isSDCardMounted() ? SystemUtil
							.getInstance().getFreeSpaceByteBySDCard()
							: SystemUtil.getInstance()
									.getFreeSpaceByteByPhoneBody();
					// 判断容量
					if (freeSpace < SharedPreferenceModule.getInstance()
							.getLong(FoneConstant.TMP_LIMIT_SIZE)) {
						FoneUtil.showToast(mContext, "存储空间不足，请进行清理");
						return;
					} else {
						if (holder.downloadStatusTv.getText().equals("操作中..")) {
							FoneUtil.showToast(mContext, "正在操作中,请稍后");
							return;
						}
						if (null != offlineCache) {
							switch (offlineCache.getCacheDownloadState()) {
							case OfflineCache.CACHE_STATE_PAUSE:
							case OfflineCache.CACHE_STATE_PAUSE_USER:
							case OfflineCache.CACHE_STATE_ERROR:
							case OfflineCache.CACHE_STATE_WAITING:
							case OfflineCache.CACHE_STATE_QWAITING:
								set2Download(holder, offlineCache);
								// FoneUtil.showToast(mContext, "设置下载,请稍后");
								break;
							case OfflineCache.CACHE_STATE_DOWNLOADING:
								set2Pause(holder, offlineCache);
								// FoneUtil.showToast(mContext, "设置暂停,请稍后");
								break;
							}
						}
					}
				} else {
					return;
				}

			}
		});

	}

	class ViewHolder {
		public TextView itemName, downloadStatusTv, seasonInfo, downloadedSize,
				totalSize, upDateInfo, collectionType;
		public ImageView itemImage, itemNew;
		public CheckBox selectedCb;
		public ProgressBar downloadProgressBar;
		public ImageButton mPlayBt;
	}

	/**
	 * 设置下载状态
	 * 
	 * @param holder
	 * @return void
	 * @throws
	 */
	private void set2Download(final ViewHolder holder, OfflineCache offlineCache) {
		offlineCache
				.setCacheDownloadState(OfflineCache.CACHE_STATE_DOWNLOADING);
		changeStatus(holder, R.drawable.collect_icon_download,
				R.color.cache_item_status_text_color, "操作中..", false);
		StorageModule.getInstance().startCache(offlineCache);
	}

	/**
	 * offlineCache@param holder
	 * 
	 * @return void
	 * @throws
	 */
	private void set2Pause(final ViewHolder holder, OfflineCache offlineCache) {
		offlineCache.setCacheDownloadState(OfflineCache.CACHE_STATE_PAUSE_USER);
		changeStatus(holder, R.drawable.collect_icon_pause,
				R.color.cache_item_status_text_color, "操作中..", false);
		StorageModule.getInstance().pauseCache(offlineCache);
	}

	/**
	 * 修改下载状态
	 * 
	 * @param holder
	 * @param drawableId
	 *            图片R文件
	 * @param textColor
	 *            下载文字颜色R文件
	 * @param statusText
	 *            下载文字内容 String格式
	 * @param isShow
	 *            是否显示图标
	 * @return void
	 * @throws
	 */
	private void changeStatus(final ViewHolder holder, int drawableId,
			int textColor, String statusText, boolean isShow) {
		Drawable drawable = mContext.getResources().getDrawable(drawableId);

		holder.downloadStatusTv.setText(statusText);
		drawable.setBounds(0, 0, drawable.getMinimumWidth(),
				drawable.getMinimumHeight());
		if (isShow) {
			holder.downloadStatusTv.setCompoundDrawables(null, drawable, null,
					null);
		} else {
			holder.downloadStatusTv
					.setCompoundDrawables(null, null, null, null);
		}
		holder.downloadStatusTv.setTextColor(mContext.getResources().getColor(
				textColor));
	}

	/**
	 * 用于更新我们想要更新的item
	 * 
	 * @param position
	 *            想更新item的下标
	 * **/
	private void updateView(int position) {

		int firstVisiblePosition = mCacheListView.getFirstVisiblePosition();

		int childIndex = position - firstVisiblePosition + 1;

		// 得到你需要更新item的View
		View view = mCacheListView.getChildAt(childIndex);

		if (view != null) {

			Object objHolder = view.getTag();

			if (objHolder instanceof ViewHolder) {

				ViewHolder viewHolder = (ViewHolder) objHolder;

				// L.v(TAG, "updateView", "name=" +
				// viewHolder.itemName.getText()
				// + viewHolder.seasonInfo.getText() + " position="
				// + position + " firstVisiblePosition="
				// + firstVisiblePosition + " childIndex=" + childIndex);

				// 设置数据
				setViewData(position, viewHolder);

			} else {

				L.e(TAG, "updateView", "position=" + position
						+ " firstVisiblePosition=" + firstVisiblePosition
						+ " childIndex=" + childIndex + " objHolder="
						+ objHolder);

			}

		} else {

			L.e(TAG, "updateView", "position=" + position
					+ " firstVisiblePosition=" + firstVisiblePosition
					+ " childIndex=" + childIndex + " view=null");

		}
	}

	/**
	 * 
	 * 更新进度
	 * 
	 * @param offlineCache
	 *            进度信息
	 * @return void
	 */
	public List<OfflineCache> setOfflineCache(OfflineCache offlineCache) {
		// L.v(TAG, "setOfflineCache", "name=" + offlineCache.getCacheName()
		// + offlineCache.getCacheEpisodeNum() + " alreadySize="
		// + offlineCache.getCacheAlreadySize() + " totalSize="
		// + offlineCache.getCacheTotalSize());
		switch (offlineCache.getCacheContentType()) {
		case OfflineCache.CACHE_CONTENT_TYPE_ANIMATION:
		case OfflineCache.CACHE_CONTENT_TYPE_TV:
		case OfflineCache.CACHE_CONTENT_TYPE_VARIETY:
			// 剧集类
			switch (offlineCache.getCacheHierarchyType()) {
			case OfflineCache.CACHE_HIERARCHY_FOLDER: {
				// 文件夹
				Integer position = mFolderOfflineCacheMap.get(offlineCache
						.getCacheCCID());
				if (position != null) {

					// L.v(TAG, "setOfflineCache",
					// "folder ccid=" + offlineCache.getCacheCCID()
					// + " position=" + position);

					OfflineCache offlineCacheFolder = mOfflineCacheList
							.get(position);

					// 更新进度
					List<OfflineCache> offlineCacheFileList = offlineCache
							.getOfflineCacheList();
					if (offlineCacheFileList != null) {
						for (OfflineCache offlineCacheFile : offlineCacheFileList) {
							offlineCacheFolder
									.addOfflineCacheFile(offlineCacheFile);
						}
						mOfflineCacheList.set(position, offlineCacheFolder);
					}

					updateView(position);
				} else {

					// 判断getView是否加载过,如果是未加载,正常
					if (mIsInitGetView) {

						L.e(TAG, "setOfflineCache", "folder ccid="
								+ offlineCache.getCacheCCID()
								+ " position=null");

					}

				}
				break;
			}
			case OfflineCache.CACHE_HIERARCHY_FILE: {
				// 文件
				Integer position = mFileOfflineCacheMap.get(offlineCache
						.getCacheCID());
				if (position != null) {

					// L.v(TAG, "setOfflineCache",
					// "name=" + offlineCache.getCacheName()
					// + offlineCache.getCacheEpisodeNum()
					// + " file cid=" + offlineCache.getCacheCID()
					// + " position=" + position);

					// 更新进度
					mOfflineCacheList.set(position, offlineCache);

					updateView(position);
				} else {

					// 判断getView是否加载过,如果是未加载,正常
					if (mIsInitGetView) {

						L.e(TAG, "setOfflineCache",
								"file cid=" + offlineCache.getCacheCID()
										+ " position=null");
					}
				}
				break;
			}
			}
			break;
		default:

			// 非剧集
			Integer position = mFolderOfflineCacheMap.get(offlineCache
					.getCacheCCID());

			if (position != null) {

				// L.v(TAG, "setOfflineCache",
				// "folder ccid=" + offlineCache.getCacheCCID()
				// + " position=" + position);

				// 更新进度
				mOfflineCacheList.set(position, offlineCache);

				updateView(position);

			} else {

				// 判断getView是否加载过,如果是未加载,正常
				if (mIsInitGetView) {

					L.e(TAG, "setOfflineCache",
							"folder ccid=" + offlineCache.getCacheCCID()
									+ " position=null");
				}

			}

			break;
		}
		return mOfflineCacheList;
	}

	public void setListView(XListView cacheListView) {
		mCacheListView = cacheListView;
	}
}
